package LC;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName LC347
 * @Description: TODO
 * @Author hl
 * @Date 2020/9/9
 * @Version V1.0
 **/
public class LC347 {
    public static void main(String[] args) {
        int[]nums={1};
        System.out.println( topKFrequent(nums,1));
    }
    public static int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],map.getOrDefault(nums[i],0)+1);
        }
        int []res=new int [k];
        int index=0;
        List<Integer>[] arr=new ArrayList[nums.length+1];
        for(int Key:map.keySet()){
            int fr=map.get(Key);
            if(arr[fr]==null){
                arr[fr]=new ArrayList<>();
            }
            arr[fr].add(Key);
        }
        for(int i=arr.length-1;i>=0&&index<k;i--){
            if(arr[i]==null){
                continue;
            }
            if(arr[i].size()<=(k-index)){
                for(int j=0;j<arr[i].size();j++){
                    res[index++]=arr[i].get(j);
                }
            }else{
                int dis=k-index;
                for(int j=0;j<dis;j++){
                    res[index+j]=arr[i].get(j);
                    index++;
                }
            }
        }

        return  res;
    }
}
